import React, { useState, useMemo, useContext, useRef, useEffect } from 'react';
import {
  View,
  navigateTo,
  router,
  Text,
  Button,
  Image,
  hideHomeButton,
  showToast,
  hideMenuButton,
  PageContainer,
} from '@ray-js/ray';
import { SwipeCell, Switch, Divider, Empty, NavBar, BottomSheet } from '@ray-js/smart-ui';

import { useDispatch, useSelector } from 'react-redux';
import { useDpSchema } from '@ray-js/panel-sdk';
import { ReduxState } from '@/redux';
import { useSystemInfo } from '@/hooks/useSystemInfo';
import { updateTimerList } from '@/redux/modules/scheduleStateSlice';

import { removeSchedule, updateStatus } from './utils';
import Strings from './i18n';
import styles from './index.module.less';
import { TimerModel } from './type';
import Res from './res';

const CloudTimingList: React.FC<any> = props => {
  const { timerList } = useSelector((state: ReduxState) => ({
    timerList: state.scheduleState.timerList,
  }));

  const { is24Hour: is24H } = useSystemInfo();
  const dispatch = useDispatch();

  const isZh = Strings.__language === 'zh';

  const handleTimingSwitch = async (v: boolean, item: TimerModel) => {
    updateStatus({ timerId: item.timerId, status: v }).then(res => {
      dispatch(updateTimerList(res));
    });
  };

  const handleTimingRemove = async (item: any) => {
    removeSchedule(item.timerId).then(res => {
      dispatch(updateTimerList(res));
    });
  };

  const handleTimingPress = item => {
    const currentInfo = JSON.stringify(item);
    router.push(`/addTimer?isEdit=true&currentInfo=${currentInfo}`);
  };

  const handleAddTiming = () => {
    router.push('/addTimer');
  };

  const dpSchema = useDpSchema();

  const renderDpsStr = dps => {
    const dpCodeList = Object.keys(dps).map(item => {
      const key = Object.values(dpSchema)?.find(dp => Number(dp.id) === +item)?.code;

      return `${Strings.getLang(key)}: ${Strings.getLang(dps[item])}`;
    });

    return dpCodeList.join('、');
  };

  const style = {
    display: 'flex',
    width: '65px',
    height: '100%',
    fontSize: '15px',
    color: '#fff',
    backgroundColor: '#ee0a24',
    justifyContent: 'center',
    alignItems: 'center',
  } as React.CSSProperties;

  const parseHour12Data = (time: string) => {
    const [hour, minute] = time.split(':').map(Number);
    const isPM = hour >= 12;
    const hour12 = hour % 12 || 12;
    const timeStr = `${hour12}:${minute.toString().padStart(2, '0')}`;
    return { timeStr, isPM };
  };

  const timings = useMemo(
    () =>
      timerList.map((item, index) => {
        console.log('🐫 ~ file: index.tsx:81 ~ item:', item);
        const loopString = item.loops
          .split('')
          .map(Number)
          .reduce((acc, cur, idx) => {
            // @ts-ignore
            if (cur === 1) acc.push(Strings.getLang(`week${idx}`));
            return acc;
          }, [])
          .join('、');

        // dps

        const timeData = is24H ? { timeStr: item.time, isPM: false } : parseHour12Data(item.time);

        return (
          <View
            style={{
              paddingInline: 30,
            }}
          >
            <View key={item.timerId} className={styles.timerItem}>
              {/* <Divider customStyle={{ marginBlock: 8 , }}  height={1} /> */}
              <SwipeCell
                key={item.timerId}
                rightWidth={65}
                slot={{
                  right: (
                    <View onClick={() => handleTimingRemove(item)} style={style}>
                      {Strings.getLang('delete')}
                    </View>
                  ),
                }}
              >
                <View className={styles.timerItemBox} onClick={() => handleTimingPress(item)}>
                  <View>
                    <View
                      style={{
                        flexDirection: isZh ? 'row' : 'row-reverse',
                        justifyContent: isZh ? 'flex-start' : 'flex-end',
                        alignItems: 'flex-end',
                      }}
                    >
                      {!is24H && (
                        <Text
                          style={{
                            fontSize: '16px',
                            color: '#333',
                            marginRight: '6px',
                            marginBottom: '3px',
                          }}
                        >
                          {Strings.getLang(`${timeData?.isPM ? 'PM' : 'AM'}`)}
                        </Text>
                      )}
                      <Text
                        style={{
                          color: '#000',
                          fontSize: '20px',
                        }}
                      >
                        {timeData.timeStr}
                      </Text>
                    </View>
                    <Text
                      style={{
                        color: '#000',
                        fontSize: 28,
                      }}
                    >
                      {loopString || Strings.getLang('once')}
                    </Text>
                    <View>
                      <Text
                        style={{
                          color: '#000',
                          fontSize: 28,
                        }}
                      >
                        {renderDpsStr(item.dps)}
                      </Text>
                    </View>
                  </View>
                  <Switch
                    checked={item.status}
                    stopClickPropagation
                    size="30"
                    onChange={event => {
                      handleTimingSwitch(event.detail, item);
                    }}
                  />
                </View>
              </SwipeCell>
            </View>
          </View>
        );
      }),
    [timerList, isZh, is24H]
  );

  const onClickLeft = React.useCallback(event => {
    router.back();
  }, []);

  useEffect(() => {
    hideMenuButton();
  }, []);

  return (
    <View className={styles.view}>
      <NavBar
        className={styles.navBar}
        title={Strings.getLang('timer_title')}
        leftArrow
        onClickLeft={onClickLeft}
      />

      {timerList.length ? (
        timings
      ) : (
        <View
          style={{
            height: '90vh',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            flexDirection: 'column',
          }}
        >
          <View className={styles.noDataBox}>
            <Image src={Res.noData} className={styles.notDataImage} />
            <Text
              style={{
                color: '#999',
                fontSize: '14px',
              }}
            >
              {Strings.getLang('noSchedule')}
            </Text>
          </View>
          <Button onClick={handleAddTiming} className={styles.addBtn}>
            <Text>{Strings.getLang('addTimer')}</Text>
          </Button>
        </View>
      )}

      {timerList.length > 0 ? (
        <View
          style={{
            width: 80,
            height: 80,
            borderRadius: 100,
            backgroundColor: '#2395ff',
            position: 'fixed',
            bottom: 100,
            right: 40,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          }}
          onClick={handleAddTiming}
        >
          <Image
            src={Res.iconAdd}
            style={{
              height: 48,
              width: 48,
              objectFit: 'contain',
            }}
          />
        </View>
      ) : null}
    </View>
  );
};

export default CloudTimingList;
